<script setup lang="ts">
import {computed, onBeforeMount, ref, watch} from "vue";
import {userConfigStore} from "@/store/user/userConfigStore";
import {createFromIconfontCN} from "@ant-design/icons-vue";
import {defaultSummary, ECode, iconFontAddress, PagePath} from "@/util/commonUtil";
import {useSystemDictStore} from "@/store/system/systemDictStore";
import _ from "lodash";
import {getUserByUid} from "@/api/user/user";
import {CountTo} from 'vue3-count-to';
import {RiseOutlined, RedoOutlined} from '@ant-design/icons-vue';
import {router} from "@/router";
import {useSysEventStore} from "@/store/system/SysEventStore";

const userData = ref<any>({})
const loginUserInfo: any = computed(() => userConfigStore().userInfo)
const isLogin = computed(() => userConfigStore().isLogin)
const userTagDictList: any = computed(() => useSystemDictStore().SysUserTag)
const userLevelImagesDictList: any = computed(() => useSystemDictStore().UserLevelImages)
const userLevelDictList: any = computed(() => useSystemDictStore().SysUserLevel)
const percentage = ref<number>(0)
const startValue = ref<number>(99)
// 引入阿里图标库
const IconFont = createFromIconfontCN({
  scriptUrl: iconFontAddress,
});

onBeforeMount(() => {
  getUserInfo(false)
})

//监听到任务完成，刷新个人信息
watch(() => [useSysEventStore().taskFinishMessage, useSysEventStore().collectMessage, useSysEventStore().praiseMessage], () => {
  getUserInfo(true)
})

function getTagName(tagId: string) {
  if (_.isEmpty(userTagDictList.value)) {
    return;
  }
  return userTagDictList.value.find((item: any) => item.dictValue == tagId)?.dictLabel
}

function getLvImage(level: any) {
  if (_.isEmpty(userLevelImagesDictList.value)) {
    return;
  }
  return userLevelImagesDictList.value[level - 1].dictValue;
}

function getPercentage() {
  if (userData.value.expValue && userData.value.levelMaxCredits) {
    percentage.value = userData.value.expValue * 100 / userData.value.levelMaxCredits;
  }
}

async function getUserInfo(refresh: boolean) {
  if (isLogin.value) {
    let params: any = new URLSearchParams()
    params.append("userUid", loginUserInfo.value.uid)
    params.append("refresh", refresh) // 是否强制刷新
    await getUserByUid(params).then((response: any) => {
      if (response.code == ECode.SUCCESS) {
        userData.value = response.data
      }
    }).finally(() => {
      getPercentage()
    })
  }
}

function valueFormat() {
  return '经验值：' + userData.value.expValue + "/" + userData.value.levelMaxCredits;
}

function getLvName(level: any) {
  if (_.isEmpty(userLevelDictList.value)) {
    return;
  }
  return userLevelDictList.value.find((item: any) => item.dictValue == level)?.remark;
}

function getUserCenter(type: string) {
  let routeData = router.resolve({
    path: PagePath.UserCenterPath,
    query: {userUid: userData.value.uid, type: type}
  });
  window.open(routeData.href, '_blank');
}

function goMedalDetail() {
  router.push(PagePath.MedalPath + loginUserInfo.value.uid)
}

function personCenterHandle(action: string) {
  // 发送个人中心领域事件
  let event = {
    "type": "personCenter",
    "action": action,
    "time": new Date(),
  }
  useSysEventStore().setDomainEventMessage(event)
}
</script>

<template>
  <div class="userIsLogin cursor-pointer" style="padding: var(--user-panel-padding)">
    <!-- 登录用户信息 -->
    <header>
      <a-row :gutter="[16,16]">
        <a-col :span="3">
          <div class="relative w-fit" @click="getUserCenter('1')">
            <a-avatar v-if="userData.photoUrl" size="large" class="h-10 w-10" :src="userData.photoUrl"
                      style="border: var(--vip-border)"/>
            <a-avatar v-else size="large" class="h-10 w-10 flex items-center justify-center">
              {{ String(userData.nickName).slice(0, 1) }}
            </a-avatar>
            <sub class="badgeSup h-4 w-4 absolute -bottom-1 -right-1" v-if="userData.userTag > 0">
              <img src="@/assets/vip/vip.svg" class="h-full w-full" alt="vipBadge">
            </sub>
          </div>
        </a-col>
        <a-col :span="21" v-if="userData">
          <div class="flex items-center gap-2">
            <span class="text-[14px] overflow-hidden font-semibold line-clamp-1"
                  :class="userData.userTag > 0 ? 'text-rose-500' : 'text-blue-500'" @click="getUserCenter('1')">
              {{ userData.nickName }}
            </span>
            <span class="userTag">
              <a-tag color="orange">
                <template #icon>
                  <IconFont type="icon-huibiao"/>
                </template>
                {{ getTagName(userData.userTag) }}
              </a-tag>
            </span>
            <span class="userGender">
              <IconFont type="icon-nanxing" v-if="userData.gender == '1'"/>
              <IconFont type="icon-nv" v-else-if="userData.gender == '2'"/>
              <IconFont type="icon-nannv" v-else/>
            </span>
            <span class="userLevel h-5 w-auto" v-if="userData.userLevel">
              <img class="w-full h-full" :src="getLvImage(userData.userLevel)" alt="userLevel">
            </span>
            <span class="rank">
              <span>排名：{{ userData.rank }}</span>
            </span>
            <span class="refresh" @click="getUserInfo(true)">
              <a-tooltip>
                <template #title>
                  每隔10分钟自动更新，点击立即刷新
                </template>
                <RedoOutlined style="color: #38bdf8"/>
              </a-tooltip>
            </span>
          </div>
          <div class="summary mt-0.5" v-if="userData">
              <span class="text-gray-400 text-[12px] line-clamp-1">
                {{ userData.summary ? userData.summary : defaultSummary }}
              </span>
          </div>
        </a-col>
      </a-row>
    </header>
    <div class="loginUserInfoMain mt-4">
      <!-- 经验等级 -->
      <a-row :gutter="[16,16]" class="flex items-center">
        <a-col :span="4">
          <a-tooltip arrow-point-at-center>
            <template #title>
              通过完成每日签到、任务、发布文章、问答、评论、动态、可获取经验值提升排名
            </template>
            <span>经验值:</span>
          </a-tooltip>
        </a-col>
        <a-col :span="14">
          <a-tooltip>
            <template #title>
              {{ valueFormat() }}
            </template>
            <a-progress :stroke-color="{'0%': '#108ee9','100%': '#87d068',}" :strokeWidth="20" :percent="percentage"
                        :show-info="false" status="active"/>
          </a-tooltip>
        </a-col>
        <a-col :span="6">
          <a-tooltip>
            <template #title>
              距离解锁下个等级还需 {{ userData.levelMaxCredits - userData.expValue }} 经验值
            </template>
            <a-tag color="purple">
              <template #icon>
                <IconFont type="icon-dengji"/>
              </template>
              {{ getLvName(userData.userLevel) }}
            </a-tag>
          </a-tooltip>
        </a-col>
      </a-row>
      <!-- 个人全站数据 -->
      <a-row :gutter="[16,16]" class="flex items-center mt-4" @click="personCenterHandle('MyArticle')">
        <a-col :span="4" class="text-center flex flex-col gap-2">
          <div class="font-bold text-blue-400 text-base">
            <CountTo :startVal='startValue' :endVal='userData.blogPublishCount' :duration='2000'></CountTo>
          </div>
          <span>
            文章
          </span>
        </a-col>
        <a-col :span="4" class="text-center flex flex-col gap-2" @click="personCenterHandle('MyComment')">
          <div class="font-bold text-blue-400 text-base">
            <CountTo :startVal='startValue' :endVal='userData.userCommentCount' :duration='2000'></CountTo>
          </div>
          <span>
            评论
          </span>
        </a-col>
        <a-col :span="4" class="text-center flex flex-col gap-2" @click="personCenterHandle('MyCollect')">
          <div class="font-bold text-blue-400 text-base">
            <CountTo :startVal='startValue' :endVal='userData.userCollectCount' :duration='2000'></CountTo>
          </div>
          <span>
            收藏
          </span>
        </a-col>
        <a-col :span="4" class="text-center flex flex-col gap-2" @click="goMedalDetail">
          <div class="font-bold text-blue-400 text-base">
            <CountTo :startVal='startValue' :endVal='userData.userMedalCount' :duration='2000'></CountTo>
          </div>
          <span>
            勋章
          </span>
        </a-col>
        <a-col :span="4" class="text-center flex flex-col gap-2" @click="getUserCenter('9')">
          <div class="font-bold text-blue-400 text-base">
            <CountTo :startVal='startValue' :endVal='userData.userMomentCount' :duration='2000'></CountTo>
          </div>
          <span>
            动态
          </span>
        </a-col>
        <a-col :span="4" class="text-center flex flex-col gap-2" @click="getUserCenter('7')">
          <div class="font-bold text-blue-400 text-base">
            <CountTo :startVal='startValue' :endVal='userData.userFollowCount' :duration='2000'></CountTo>
          </div>
          <span>
            粉丝
          </span>
        </a-col>
      </a-row>
      <!-- 个人勋章 -->
      <a-row :gutter="[16,16]" class="flex items-center mt-4">
        <a-col :span="5">
          <a-tooltip>
            <template #title>
              活跃社区解锁海量勋章
            </template>
            <span>获得勋章:</span>
          </a-tooltip>
        </a-col>
        <a-col :span="18">
          <div v-if="!_.isEmpty(userData.userMedalList)" v-for="(medal, index) in userData.userMedalList"
               :key="medal.uid">
            <div v-if="index < 7">
              <a-tooltip>
                <template #title>
                  {{
                    medal.name + '[约' + medal.gainProbability + '用户获取]'
                  }}
                </template>
                <img v-if="medal.fileUrl" :src="medal.fileUrl" width="32px" height="32px"
                     class="float-left h-[32px] w-[32px] cursor-pointer transition-all" alt="medal"
                     data-fancybox="gallery" :data-caption="medal.name"/>
              </a-tooltip>
            </div>
          </div>
          <div v-else @click="goMedalDetail">
            <span class="text-gray-400">暂未获得勋章</span>
          </div>
        </a-col>
      </a-row>
      <!-- 七日新增数据 -->
      <a-row :gutter="[16,16]" class="flex items-center mt-4 bg-gray-100 rounded-xl pt-4 pb-4">
        <a-col :span="12" class="text-center flex flex-col gap-2">
          <span>7日新增阅读数</span>
          <div class="font-bold text-green-600 text-base">
            <countTo :startVal='startValue' :endVal='userData.webVisitCountByWeek' :duration='2000'/>
            <RiseOutlined class="ml-2"/>
          </div>
        </a-col>
        <a-col :span="12" class="text-center flex flex-col gap-2">
          <span>7日新增点赞数</span>
          <div class="font-bold text-green-600 text-base">
            <countTo :startVal='startValue' :endVal='userData.praiseCountByWeek' :duration='2000'/>
            <RiseOutlined class="ml-2"/>
          </div>
        </a-col>
      </a-row>
    </div>
  </div>
</template>

<style scoped lang="less">
:deep(.ant-tag) {
  margin-inline-end: 0;
}

:deep(.ant-tag >.anticon+span) {
  margin-left: 4px;
}

:deep(.ant-progress-line) {
  margin-bottom: 0;
}
</style>
